<?php
namespace app\index\controller;

use app\common\exception\System as SystemException;
use app\common\exception\User as UserException;
use app\common\exception\Image as ImageException;
use app\common\model\MemberAccount;
use app\common\model\Members;
use app\common\model\Config as ConfigModel;
use app\common\validate\User as UserValidate;
use app\common\exception\SmsCode as SmsCodeException;
use http\Http;
use Session;
use Exception;
use Hook;
use Config;
use Cache;
use random\Random;
use think\facade\Env;

class User extends Common
{
	/**
	 * 不需要登录
	 * @var array
	 */
	protected $noNeedLogin = ['login', 'register', 'buildToken','version', 'forgetPwd'];

	/**
	 * 不需要鉴权
	 * @var array
	 */
	protected $noNeedRight = ['*'];

	/**
	 * 初始化
	 */
	protected function initialize()
    {
        parent::initialize();
        $auth = $this->auth;

        // 监听注册登录注销的事件
        Hook::add('user_login_failure', function ($user) {
        	// 登录失败次数
			$user->login_failure_date = strtotime(date('Y-m-d'));
			$user->login_failure      = $user->login_failure+1;
			$user->save();
        });

        // 单点登录
        Hook::add('user_login_successed', function ($token) {
            Session::set('login_token', $token);
        });

        Hook::add('user_register_successed', function ($token) {
            Session::set('login_token', $token);
        });

        Hook::add('user_logout_successed', function ($user) {
        	// 登录失败次数
			$user->token = '';
			$user->save();
            Session::delete('login_token');
        });
    }

	/**
	 * 登录
	 */
	public function login()
	{
		if ($this->auth->member_id) {
			return $this->errorReturn(UserException::E_IS_LOGIN, UserException::$messageList[UserException::E_IS_LOGIN]);
		}

		$data = [
			'phone'      => $this->request->post('phone'),
			'password'   => $this->request->post('password')
		];

        $validate = new UserValidate;
        if (!$validate->scene('login')->check($data)) {
            return $this->errorReturn(SystemException::E_VALIDATE, $validate->getError());
        }
        $message = service('common/User')->login($data, $this->auth);
        try {

        } catch (UserException $userE) {
        	return $this->errorReturn($userE->getCode(), $userE->getMessage());
        } catch (Exception $e) {
            return $this->errorReturn(SystemException::E_DEFAULT, SystemException::getErrorMsg(SystemException::E_DEFAULT));
        }

        return $this->successReturn(['auth' => $message['auth'], 'user_id' => $message['user_id']], SystemException::E_SUCCESS, '登入成功');
	}

	/**
	 * 注册
	 */
	public function register()
	{
		if ($this->auth->member_id) {
			return $this->errorReturn(UserException::E_IS_LOGIN, UserException::$messageList[UserException::E_IS_LOGIN]);
		}

		$data = [
			'phone'      => $this->request->post('phone'),
			'password'   => $this->request->post('password'),
			'repassword' => $this->request->post('repassword'),
			'code'       => $this->request->post('code'),
			'phone_code' => $this->request->post('phone_code')
		];
		$rule = [
			'phone'         => [
                'require',
                'max'    => 11,
                'regex'  => '/^((13[0-9])|(14[5,7])|(15[0-3,5-9])|16[5]|16[6]|(17[0,3,5-8])|(18[0-9])|19[89])\d{8}$/',
              //  'unique:members',
            ],
	        'password'      => 'require|min:6|max:20',
	        'repassword'    => 'confirm:password',
			//'code'          => 'require'
		];

		$validate = $this->validate($data, $rule);
        if ($validate !== true) {
            return $this->errorReturn(SystemException::E_VALIDATE, $validate);
        }
        
        $message = service('common/User')->register($data, $this->auth);

        return $this->successReturn(['auth' => $message['auth'], 'user_id' => $message['user_id']], SystemException::E_SUCCESS, '注册成功');
	}

	/**
	 * 忘记密码
	 */
	public function forgetPwd()
	{
		$data = [
			'phone'      => $this->request->post('phone'),
			'password'      => $this->request->post('password'),
			'phone_code'      => $this->request->post('phone_code')
		];

		$rule = [
			'phone' => 'require',
			'password' => 'require',
			'phone_code' => 'require',
		];

        $validate = $this->validate($data, $rule);
        if ($validate !== true) {
            return $this->errorReturn(SystemException::E_VALIDATE, $validate);
        }

        $mobile = input('post.phone');
        $codeKey = 'forgetPwd:'.$mobile;
        $codes = Cache::store('redis')->handler()->get($codeKey);
        if (empty($codes)) {
          exception(SmsCodeException::getErrorMsg(SmsCodeException::E_CODE_EXPIRE, SmsCodeException::E_CODE_EXPIRE));
        } else if ($codes != $data['phone_code']) {
          exception(SmsCodeException::getErrorMsg(SmsCodeException::E_CODE_NO),SmsCodeException::E_CODE_NO);
        }
      $message = service('common/User')->forgetPwd($data);
      return $this->successReturn($message, SystemException::E_SUCCESS, '修改成功');
        try {

        } catch (SmsCodeException $SmsCodeException) {
            return $this->errorReturn($SmsCodeException->getCode(), $SmsCodeException->getMessage());
        } catch (\Exception $exception) {
            return $this->errorReturn(SystemException::E_DEFAULT, SystemException::getErrorMsg(SystemException::E_DEFAULT));
        }
	}

	/**
	 * 退出
	 */
	public function logout()
	{
		if (!$this->auth->member_id) {
			return $this->errorReturn(UserException::E_NOT_LOGIN, UserException::$messageList[UserException::E_NOT_LOGIN]);
		}

        try {
        	$this->auth->logout();
        } catch (Exception $e) {
            return $this->errorReturn(SystemException::E_DEFAULT, SystemException::getErrorMsg(SystemException::E_DEFAULT));
        }

        return $this->successReturn(NULL, SystemException::E_SUCCESS, '退出成功');
	}

	/**
	 * 获取表单token
	 */
	public function buildToken()
	{
        return $this->successReturn(['__token__' => $this->request->token()], SystemException::E_SUCCESS);
	}

    /**
     * 会员昵称编辑
     */
    public function editUserName()
    {
    	$data = [
			'username'      => $this->request->post('username'),
	        // '__token__'  => $this->request->post('__token__'),
		];
		$rule = [
			'username'          => 'require'
		];
		$validate = $this->validate($data, $rule);
        if ($validate !== true) {
            return $this->errorReturn(SystemException::E_VALIDATE, $validate);
        }

        try {
        	$message = service('common/User')->editUserName($data, $this->auth);
        } catch (UserException $userE) {
        	if($this->auth->_code_error != ''){
        		return $this->errorReturn($userE->getCode(), $this->auth->_code_error);
        	}
        	return $this->errorReturn($userE->getCode(), $userE->getMessage());
        } catch (SmsCodeException $SmsCodeException) {
        	return $this->errorReturn($SmsCodeException->getCode(), $SmsCodeException->getMessage());
        } catch (Exception $e) {
            return $this->errorReturn(SystemException::E_DEFAULT, SystemException::getErrorMsg(SystemException::E_DEFAULT));
        }

        return $this->successReturn('', SystemException::E_SUCCESS, '修改成功');
    }

    /*
	 *修改头像
	 */
	public function avatar(){
		try {
			$file = request()->file('file');
			$image = \think\Image::open(request()->file('file'));
			$width  = $image->width();
			$height = $image->height();
			$mime   = $image->mime();
			$size   = $image->size();
			$type   = $image->type();
			$configLimit = Config::get('app.img_limit');
			if($file->getSize() > $configLimit['size']){
				return $this->errorReturn( ImageException::E_SIZE_NOT_MATCH, ImageException::getErrorMsg(ImageException::E_SIZE_NOT_MATCH) );
			}

			if(!in_array($mime, $configLimit['mine'])){
				return $this->errorReturn( ImageException::E_MINE_NOT_MATCH, ImageException::getErrorMsg(ImageException::E_MINE_NOT_MATCH) );
			}

			if(!in_array($type, $configLimit['ext'])){
				return $this->errorReturn( ImageException::E_EXT_NOT_MATCH, ImageException::getErrorMsg(ImageException::E_EXT_NOT_MATCH) );
			}
			if($width >= Config::get('img_limit.wtdth')){
				$wid = Config::get('img_limit.wtdth');
			}else{
				$wid = $width;
			}
			if($height >= $configLimit['height']){
				$heig = $configLimit['height'];
			}else{
				$heig = $height;
			}
			$name = Random::uuid();
			$date = date('Ymd',time());
			directory(Env::get('root_path') . 'public/uploads/avatar/' . $date);
			$res = $image->thumb($wid, $heig, \think\Image::THUMB_FIXED)->save(Env::get('root_path') . 'public/uploads/avatar/' . $date . '/'. $name .'.'. $image->type());

			if($res){
				$message = service('common/User')->avatar($date . '/'. $name .'.'. $image->type(), $this->auth);
			    return $this->successReturn(['url' => file_url( $date .'/'. $name .'.'. $image->type() ) ], SystemException::E_SUCCESS);
			}
		} catch (Exception $e) {
            return $this->errorReturn( SystemException::E_DEFAULT, SystemException::getErrorMsg(SystemException::E_DEFAULT) );
		}
	}

  /**
   * 校验支付密码
   * @return \think\Response
   */
	public function checkPayPassword() {
      if (!$this->auth->member_id) {
        return $this->errorReturn(UserException::E_IS_LOGIN, UserException::$messageList[UserException::E_IS_LOGIN]);
      }
      $pay_password = trim($this->request->post('pay_password'));
      if (empty($pay_password)) {
        return $this->errorReturn(SystemException::E_DEFAULT, '參數不對');
      }
      try {
        $userInfo = $this->auth->getUser();
        if (!$userInfo) {
          exception(UserException::getErrorMsg(UserException::E_PASSWORD), UserException::E_PASSWORD, $this->_exceptions['user']);
        }
        $res_pay_password = $this->auth->getEncryptPassword($pay_password, $userInfo['salt']);
        $res = $this->auth->checkEncryptPassword($userInfo['pay_password'], $pay_password, $userInfo['salt']);
        if (!$res)
        {
          return $this->errorReturn(UserException::getErrorMsg(UserException::E_PAYPASSWORD));
        }
        return $this->successReturn(1, SystemException::E_SUCCESS, '校驗成功');
      } catch (UserException $userE) {
        return $this->errorReturn($userE->getCode(), $userE->getMessage());
      } catch (Exception $e) {
        return $this->errorReturn(SystemException::E_DEFAULT, SystemException::getErrorMsg(SystemException::E_DEFAULT));
      }
	}

  /**
   * 设置支付密码
   * @return \think\Response
   */
    public function setPayPassword()
    {
      if (!$this->auth->member_id) {
        return $this->errorReturn(UserException::E_IS_LOGIN, UserException::$messageList[UserException::E_IS_LOGIN]);
      }
      $data = [
        'pay_password'   => trim($this->request->post('pay_password'))
      ];

      // 短信验证码
      $phone_code = intval(input('post.code'));
      $codeKey = 'pay_password:'.$this->auth->phone;
      $codes = Cache::store('redis')->handler()->get($codeKey);
      if (empty($codes)) {
        return $this->errorReturn(SmsCodeException::E_CODE_EXPIRE, SmsCodeException::getErrorMsg(SmsCodeException::E_CODE_EXPIRE));
      } else if ($codes != $phone_code) {
        return $this->errorReturn(SmsCodeException::E_CODE_NO, SmsCodeException::getErrorMsg(SmsCodeException::E_CODE_NO));
      }

      try {
        $userInfo = $this->auth->getUser();
        if (!$userInfo) {
          exception(UserException::getErrorMsg(UserException::E_PASSWORD), UserException::E_PASSWORD, $this->_exceptions['user']);
        }
        // 修改支付密码
        $memberModel = model('common/Members');
        $pay_password = $this->auth->getEncryptPassword($data['pay_password'], $userInfo['salt']);
        $res = $memberModel->where(['member_id' => $this->auth->member_id])->update(['pay_password' => $pay_password]);
      } catch (UserException $userE) {
        return $this->errorReturn($userE->getCode(), $userE->getMessage());
      }
      return $this->successReturn($res, SystemException::E_SUCCESS, '設定成功');

    }

  public function info()
  {
    if (!$this->auth->member_id) {
      return $this->errorReturn(UserException::E_IS_LOGIN, UserException::$messageList[UserException::E_IS_LOGIN]);
    }
    $memberInfo['username'] = $this->auth->username;
    $memberInfo['nickname'] = $this->auth->nickname;
    $memberInfo['phone'] = $this->auth->phone;
    $memberInfo['email'] = $this->auth->email;
    $memberInfo['code'] = $this->auth->code;
    $memberInfo['is_vip'] = $this->auth->is_vip;
    $memberInfo['account'] = $this->auth->account;
    $memberInfo['gold'] = $this->auth->gold;
    $memberInfo['avatar'] = $this->auth->avatar;
    $memberInfo['is_personal_cert'] = $this->auth->is_personal_cert;
    $memberInfo['is_business_cert'] = $this->auth->is_business_cert;
    return $memberInfo;
  }
}
